package com.wt.service.service.impl;

import com.wt.dao.demo.mapper.LoginTimesMapper;
import com.wt.dao.demo.model.LoginTimes;
import com.wt.dao.demo.model.UserLogin;
import com.wt.service.exception.WTException;
import com.wt.service.service.LoginService;
import com.wt.service.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service("loginService")
public class LoginServiceImpl implements LoginService
{
    private final static Logger LOGGER = Logger.getLogger(LoginServiceImpl.class);

    @Autowired
    private UserService userService;

    @Autowired
    private LoginTimesMapper loginTimesMapper;

    public Integer login(String loginName, String passWord, HttpServletRequest request) throws Exception {
        UserLogin userLogin = userService.selectUserLoginByUserNameAndPassWord(loginName,passWord);
        if(null != userLogin)
        {
            addLoginHistory(userLogin.getUserId(),request);
            return userLogin.getUserId();
        }
        return null;
    }

    public LoginTimes getLoginTimes(Integer userId, HttpServletRequest request) throws Exception {
        LoginTimes loginTimes = new LoginTimes();
        loginTimes.setUserId(userId);
        loginTimes.setIp(request.getRemoteAddr());
        LoginTimes resultLoginTimes = loginTimesMapper.selectByLoginTimes(loginTimes);
        return resultLoginTimes;
    }

    /**
     * 加入登录历史
     * @param request
     */
    private void addLoginHistory(final Integer userId, final HttpServletRequest request) {

        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(new Runnable() {
            public void run() {
                String ip = request.getRemoteAddr();
                LoginTimes loginTimes = new LoginTimes();
                loginTimes.setUserId(userId);
                loginTimes.setIp(ip);
                LoginTimes resultLoginTimes = loginTimesMapper.selectByLoginTimes(loginTimes);
                if(null != resultLoginTimes)
                {
                    resultLoginTimes.setTimes(resultLoginTimes.getTimes()+1);
                    loginTimesMapper.updateByPrimaryKey(resultLoginTimes);
                }
                else
                {
                    loginTimes.setTimes(1);
                    loginTimesMapper.insertSelective(loginTimes);
                }
            }
        });

    }
}
